package com.vm.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.LocalUserInfoDao;
import com.vm.model.ActiveSoft;
import com.vm.model.LocalUserInfo;
import com.vm.model.News;
import com.vm.model.Soft;
import com.vm.model.UserSign;
import com.vm.model.UserSignDetail;
import com.vm.utils.JsonUtils;
import com.wwt.app.R;

import android.R.color;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.opengl.Visibility;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月14日 下午5:03:11]
 * @Version: [v1.0]
 * 
 */
public class SignActivity extends Activity {
	protected static final String TAG = "SignActivity";
	LinearLayout rlayout_week;
	Button btn_sign_in;
	Button btn_signed_in;
	private LocalUserInfoDao luidao;
	private LocalUserInfo userInfo;
	private RequestQueue mQueue;
	TextView tv_continuous_days;
	TextView tv_total;
	TextView tv_warning;
	int times = -1;
	UserSign userSign;
	ImageView imgbtn_search_back;

	private HashMap<String, Boolean> signHashMap;

	private List<String> list = new ArrayList<String>();
	private GridView gdDate;
	// private GridView gdWeek;
	private int dayMaxNum;
	private int year, month, day, ym;
	Time t = new Time();
	TextView tv_NowDate;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sign_in);

		init();
		initCalender();

		mQueue = Volley.newRequestQueue(this);
		luidao = new LocalUserInfoDao(this);
		userInfo = luidao.query();
		if (userInfo != null) {
			String url = VMConst.REQUEST_URL + "ifSign?userId="
					+ userInfo.getUserId();
			JsonObjectRequest stringRequest = new JsonObjectRequest(url, null,
					new Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {

							userSign = JsonUtils.jsonToBean(response,
									UserSign.class);
							if (userSign != null) {
								times = userSign.getTimes();
								String today = StringUtil.getDate(4);

								android.util.Log.i(TAG, userSign.getLast());
								android.util.Log.i(TAG, Integer.toString(times));
								android.util.Log.i(TAG,
										Integer.toString(userSign.getTotal()));
								if (!today.equals(userSign.getLast())) {

									btn_sign_in.setVisibility(View.VISIBLE);
									btn_sign_in
											.setOnClickListener(btnClickListener);
								} else {
									btn_signed_in.setVisibility(View.VISIBLE);
								}
								tv_total.setText(Integer.toString(userSign
										.getTotal()));
							} else {
								times = 0;
								btn_sign_in.setVisibility(View.VISIBLE);
								btn_sign_in
										.setOnClickListener(btnClickListener);
							}
							tv_continuous_days.setText(Integer.toString(times));
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError arg0) {
							btn_sign_in.setVisibility(View.VISIBLE);
							btn_sign_in.setOnClickListener(btnClickListener);
						}
					});

			mQueue.add(stringRequest);

			signHashMap = new HashMap<String, Boolean>();
			String url2 = VMConst.REQUEST_URL + "getDetails?userId="
					+ userInfo.getUserId();
			JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url2,
					new Listener<JSONArray>() {

						@Override
						public void onResponse(JSONArray response) {
							for (int i = 0; i < response.length(); i++) {
								try {
									JSONObject jsonObject = response
											.getJSONObject(i);
									final UserSignDetail userSignDetail = JsonUtils
											.jsonToBean(jsonObject,
													UserSignDetail.class);

									int day = Integer.parseInt(userSignDetail
											.getStime().substring(8, 10));
									signHashMap.put(Integer.toString(day), true);

									initData();

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {

						}
					});
			mQueue.add(jsonArrayRequest);

		} else {
			tv_warning.setVisibility(View.VISIBLE);
			rlayout_week.setVisibility(View.GONE);
		}

	}

	/**
	 * 初始化
	 */
	private void init() {
		rlayout_week = (LinearLayout) findViewById(R.id.rlayout_week);
		btn_sign_in = (Button) findViewById(R.id.btn_sign_in);
		btn_signed_in = (Button) findViewById(R.id.btn_signed_in);
		tv_continuous_days = (TextView) findViewById(R.id.tv_continuous_days);
		tv_total = (TextView) findViewById(R.id.tv_total);
		tv_warning = (TextView) findViewById(R.id.tv_warning);
		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
	}

	public void initCalender() {
		tv_NowDate = (TextView) findViewById(R.id.tv_NowDate);
		t.setToNow();
		year = t.year;
		// year = 2015;
		month = t.month + 1;
		// month = 3;
		day = t.monthDay;
		// day = 25;
		final String date = year + "-" + month + "-" + day;
		tv_NowDate.setText(date);
		// sdao.open();

	}

	public void initData() {
		gdDate = (GridView) findViewById(R.id.gv_calender);
		// gdWeek = (GridView) findViewById(R.id.gv_week);
		gdDate.setFocusable(false);
		// gdWeek.setFocusable(false);
		// gdWeek.setSelector(new ColorDrawable(Color.TRANSPARENT));
		// getWeekAdapter myAdapter = new getWeekAdapter();
		// gdWeek.setAdapter(myAdapter);
		// 查询当月已签到的日期
		list.clear();
		dayMaxNum = getDaysByYearMonth(year, month);
		SimpleDateFormat dateFm = new SimpleDateFormat("E");
		// 查出当月1号是周几，从周一开始到周日
		String dayofWeek = dateFm.format(new Date(year, month - 1, 1));

		// 从周一开始到周日分别为0,1,2,...
		char dayofweek2 = dayofWeek.toCharArray()[1];
		// Log.i(TAG, dayofweek);
		int spaceNum = 0;
		// 计算日历1号之前的空位数
		switch (dayofweek2) {

		// case '一':
		// spaceNum = 1;
		// break;
		case '二':
			spaceNum = 1;
			break;
		case '三':
			spaceNum = 2;
			break;
		case '四':
			spaceNum = 3;
			break;
		case '五':
			spaceNum = 4;
			break;
		case '六':
			spaceNum = 5;
			break;
		case '日':
			spaceNum = 6;
			break;

		default:
			break;
		}

		for (int i = 0; i < spaceNum; i++) {
			list.add(i, "no");
		}
		dayMaxNum += spaceNum;
		for (int i = spaceNum; i < dayMaxNum; i++) {
			list.add(i, i - spaceNum + 1 + "");
		}
		if (dayMaxNum % 7 != 0) {
			for (int i = dayMaxNum; i < dayMaxNum + (7 - (dayMaxNum % 7)); i++) {
				list.add(i, "no");
			}
		}
		Log.i(TAG, Integer.toString(list.size()));
		gdDate.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gdDate.setAdapter(new getDayNumAdapter(getApplicationContext()));

	}

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	/*
	 * 点击签到
	 */
	OnClickListener btnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (userInfo != null) {

				String typeName = "签到";
				try {
					typeName = URLEncoder.encode(typeName, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String url = VMConst.REQUEST_URL + "sign?userId="
						+ userInfo.getUserId() + "&stime="
						+ StringUtil.getDate(4) + "&typeName=" + typeName;
				StringRequest stringRequest = new StringRequest(url,
						new Listener<String>() {
							@Override
							public void onResponse(String response) {

								if (!response.equals("0")) {
									// tv_continuous_days.setText(Integer
									// .toString(times + 1));
									btn_sign_in.setVisibility(View.GONE);
									btn_signed_in.setVisibility(View.VISIBLE);
									btn_signed_in.setEnabled(false);
									// int addIntergral = 10;
									// if (times / 5 >= 1 && times % 5 == 0) {
									// addIntergral = times / 5 * 15;
									// }
									CurrentUser.INTERGRAL = CurrentUser.INTERGRAL
											+ Integer.parseInt(response);
									int pretotal = Integer.parseInt(tv_total
											.getText().toString());
									tv_total.setText(Integer.toString(Integer
											.parseInt(response) + pretotal));
									int times = Integer
											.parseInt(tv_continuous_days
													.getText().toString()) + 1;
									tv_continuous_days.setText(Integer
											.toString(times));
									luidao.update();
								} else {
									Toast toast = Toast.makeText(
											SignActivity.this, "签到失败",
											Toast.LENGTH_SHORT);
									toast.show();
								}
							}
						}, null);

				mQueue.add(stringRequest);

			}
		}
	};

	// class getWeekAdapter extends BaseAdapter {
	// String[] week = new String[] { "日", "一", "二", "三", "四", "五", "六" };
	//
	// @Override
	// public int getCount() {
	// // TODO Auto-generated method stub
	// return week.length;
	// }
	//
	// @Override
	// public Object getItem(int position) {
	// // TODO Auto-generated method stub
	// return null;
	// }
	//
	// @Override
	// public long getItemId(int position) {
	// // TODO Auto-generated method stub
	// return position;
	// }
	//
	// @Override
	// public View getView(int position, View convertView, ViewGroup parent) {
	// // TODO Auto-generated method stub
	// if (convertView == null) {
	// // 根据布局文件获取View返回值
	// convertView = LayoutInflater.from(getApplicationContext())
	// .inflate(R.layout.sign_in_weekitem, null);
	// }
	// TextView tv_week = (TextView) convertView
	// .findViewById(R.id.tv_week);
	// tv_week.setText(week[position]);
	// return convertView;
	// }
	//
	// }

	class getDayNumAdapter extends BaseAdapter {
		Context c;

		public getDayNumAdapter(Context c) {
			this.c = c;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = LinearLayout.inflate(c, R.layout.sign_in_item, null);
			// TextView txtWeek = (TextView) v.findViewById(R.id.tv_week);
			TextView txtDay = (TextView) v.findViewById(R.id.tv_date);
			Button btn_sign_supplement = (Button) v
					.findViewById(R.id.btn_sign_supplement);
			// Button btn_signed = (Button) v.findViewById(R.id.btn_signed);

			// switch (position) {
			// case 0:
			// txtWeek.setText("日");
			// break;
			// case 1:
			// txtWeek.setText("一");
			// break;
			// case 2:
			// txtWeek.setText("二");
			// break;
			// case 3:
			// txtWeek.setText("三");
			// break;
			// case 4:
			// txtWeek.setText("四");
			// break;
			// case 5:
			// txtWeek.setText("五");
			// break;
			// case 6:
			// txtWeek.setText("六");
			// break;
			// }
			//
			// if (position < 7) {
			// txtWeek.setVisibility(View.VISIBLE);
			// }

			if (list.get(position).equals("no")) {
				txtDay.setText("");
				btn_sign_supplement.setVisibility(View.GONE);
			} else {
				int lstDay = Integer.parseInt(list.get(position));

				// 标记当前日期
				if (day == lstDay) {
					txtDay.setText(list.get(position).toString());
					txtDay.setTextColor(Color.RED);
				} else
					txtDay.setText(list.get(position).toString());
				if (day < lstDay) {
					btn_sign_supplement.setVisibility(View.VISIBLE);
				}
				if (signHashMap.containsKey(Integer.toString(lstDay))) {
					btn_sign_supplement
							.setBackgroundResource(R.drawable.signed_in);
					// btn_signed.setVisibility(View.VISIBLE);
				} else if (day > lstDay) {
					btn_sign_supplement.setBackgroundColor(Color
							.parseColor("#ff9131"));
					btn_sign_supplement.setText("补签");
					btn_sign_supplement.setTextColor(Color.WHITE);
					btn_sign_supplement.setTextSize(TypedValue.COMPLEX_UNIT_SP,
							15);
				}
			}

			return v;
		}

	}

	// // 获取当月的天数
	// public static int getCurrentMonthDay() {
	// Calendar a = Calendar.getInstance();
	// a.set(Calendar.DATE, 1);
	// a.roll(Calendar.DATE, -1);
	// int maxDate = a.get(Calendar.DATE);
	// return maxDate;
	// }

	/**
	 * 根据年 月 获取对应的月份 天数
	 * */
	public static int getDaysByYearMonth(int year, int month) {

		Calendar a = Calendar.getInstance();
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, month - 1);
		a.set(Calendar.DATE, 1);
		a.roll(Calendar.DATE, -1);
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	public static void main(String[] args) {
		// SimpleDateFormat dateFm = new SimpleDateFormat("E");
		// // 查出当月1号是周几，从周一开始到周日
		// String dayofWeek = dateFm.format(new Date(year, month - 1, 1));
	}
}
